#include "../include/soundplayer.h"
#include <vorbis/codec.h>
#include <vorbis/vorbisfile.h>
#include <unistd.h>

environment_t env;


void play_ogg(FILE* input){
	if (env->status != SP_IDLE) goto END;
	env->status = SP_PLAY;

	//declaring stuff
	int current_section;
	char buffer[BUF_SIZE];
	OggVorbis_File vf;
	struct vorbis_info *f;
	long status, marker;

	if (ov_open_callbacks(input, &vf, NULL, 0, OV_CALLBACKS_NOCLOSE) < 0) env->message("Input does not appear to be an Ogg bitstream.\n");

	//analysys
	if((f = ov_info(&vf, current_section)) == NULL){ env->message("Can't find info\n"); }
	else {
		if(FLAGUNSET(SP_OVERRIDE_HERTZ)) { marker = 1; env->rate = f->rate; } //syncronize bitrate
		if(FLAGUNSET(SP_OVERRIDE_CHANNEL)) { marker = 1; env->channels = f->channels; } //and channels
		if(marker) { marker = 0; pcm_output_configure(); } //don't reconfigure the soundcard 10 times per second
	}

	do {
		//handle all statuses in 3 lines
		if (env->status > SP_PLAY) {
			while (env->status == SP_PAUSE) sleep(1);
			if (env->status > SP_PAUSE) goto CLEANUP;
		}


		status = ov_read(&vf, buffer, BUF_SIZE, 0, 2, 1, &current_section);

		if ( env->progress != NULL) env->progress(ftell(input), env->size);
		pcm_output_write(buffer, pcm_output_bytes_to_frames(status));
	} while (status != 0);

	CLEANUP:
	ov_clear(&vf);
	env->status = SP_IDLE;

	END:
		;
}
